<!--
// Copyright © 2023 Hardcore Engineering Inc.
//
// Licensed under the Eclipse Public License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. You may
// obtain a copy of the License at https://www.eclipse.org/legal/epl-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
-->
<script lang="ts">
  import calendar from '@hcengineering/calendar'
  import { getCurrentEmployee } from '@hcengineering/contact'
  import { getCurrentAccount } from '@hcengineering/core'
  import { getClient } from '@hcengineering/presentation'
  import { ToDo } from '@hcengineering/time'
  import { CheckBox, Label } from '@hcengineering/ui'
  import time from '../plugin'
  import WorkItemPresenter from './WorkItemPresenter.svelte'

  export let value: ToDo
  export let withoutSpace: boolean = false
  export let withouthWorkItem: boolean = false
  export let showCheck = false

  function isVisible (value: ToDo): boolean {
    if (value.createdBy !== undefined && getCurrentAccount().socialIds.includes(value.createdBy)) return true
    if (value.visibility === 'public') {
      return true
    }
    return false
  }

  $: visible = isVisible(value)

  const me = getCurrentEmployee()

  $: readonly = value.user !== me || updating !== undefined

  const client = getClient()

  let updating: Promise<any> | undefined = undefined

  async function markDone (): Promise<void> {
    await updating
    updating = client.update(value, { doneOn: value.doneOn == null ? Date.now() : null })
    await updating
    updating = undefined
  }
</script>

{#if showCheck}
  <div class="flex-row-center items-start">
    <div class="mt-0-5">
      <CheckBox {readonly} checked={value.doneOn != null} kind={'positive'} size={'medium'} on:value={markDone} />
    </div>
    <div class="ml-2 flex-col">
      <div class="overflow-label flex-no-shrink">
        {#if visible}
          {value.title}
        {:else}
          <Label label={calendar.string.Busy} />
        {/if}
      </div>
      {#if value.attachedTo !== time.ids.NotAttached && visible && !withouthWorkItem}
        <div class:mt-1={value.title}>
          <WorkItemPresenter todo={value} {withoutSpace} />
        </div>
      {/if}
    </div>
  </div>
{:else}
  <div class="flex-col flex-gap-1">
    <div class="overflow-label flex-no-shrink">
      {#if visible}
        {value.title}
      {:else}
        <Label label={calendar.string.Busy} />
      {/if}
    </div>
    {#if value.attachedTo !== time.ids.NotAttached && visible && !withouthWorkItem}
      <div>
        <WorkItemPresenter todo={value} {withoutSpace} />
      </div>
    {/if}
  </div>
{/if}
